package cn.wolfcode.business.controller;

import cn.wolfcode.business.domain.BusCarPackageAudit;
import cn.wolfcode.business.domain.BusServiceItem;
import cn.wolfcode.business.service.IBusCarPackageAuditService;
import cn.wolfcode.business.service.IBusServiceItemService;
import cn.wolfcode.common.core.controller.BaseController;
import cn.wolfcode.common.core.domain.AjaxResult;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工作流任务处理Controller（临时测试用）
 * 
 * @author system
 * @date 2025-09-27
 */
@RestController
@RequestMapping("/business/workflow")
public class BusWorkflowController extends BaseController {
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private RuntimeService runtimeService;
    
    @Autowired
    private IBusCarPackageAuditService auditService;
    
    @Autowired
    private IBusServiceItemService serviceItemService;

    /**
     * 获取当前用户的待办任务
     */
    @GetMapping("/tasks")
    public AjaxResult getTasks(@RequestParam(required = false) String assignee) {
        List<Task> tasks;
        if (assignee != null && !assignee.isEmpty()) {
            tasks = taskService.createTaskQuery()
                    .taskAssignee(assignee)
                    .list();
        } else {
            // 获取所有待办任务
            tasks = taskService.createTaskQuery().list();
        }
        return AjaxResult.success(tasks);
    }

    /**
     * 完成任务（审核通过）
     */
    @PostMapping("/complete/{taskId}")
    public AjaxResult completeTask(@PathVariable String taskId, 
                                   @RequestParam(defaultValue = "true") Boolean approved,
                                   @RequestParam(required = false) String comment) {
        try {
            // 获取任务信息
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            if (task == null) {
                return AjaxResult.error("任务不存在");
            }

            // 设置任务变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("approved", approved);
            if (comment != null && !comment.isEmpty()) {
                variables.put("comment", comment);
            }

            // 完成任务
            taskService.complete(taskId, variables);

            // 检查流程是否结束
            String processInstanceId = task.getProcessInstanceId();
            boolean isProcessEnded = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult() == null;

            if (isProcessEnded) {
                // 流程结束，更新业务数据
                updateBusinessData(processInstanceId, approved);
            }

            return AjaxResult.success("任务完成成功");
        } catch (Exception e) {
            return AjaxResult.error("任务完成失败：" + e.getMessage());
        }
    }

    /**
     * 根据流程实例ID获取审核记录
     */
    @GetMapping("/audit/{processInstanceId}")
    public AjaxResult getAuditByProcessInstanceId(@PathVariable String processInstanceId) {
        // 这里需要根据流程实例ID查询审核记录
        // 由于没有直接的查询方法，我们需要遍历查找
        List<BusCarPackageAudit> auditList = auditService.selectBusCarPackageAuditList(new BusCarPackageAudit());
        for (BusCarPackageAudit audit : auditList) {
            if (processInstanceId.equals(audit.getInstanceId())) {
                return AjaxResult.success(audit);
            }
        }
        return AjaxResult.error("未找到对应的审核记录");
    }

    /**
     * 快速审核通过（测试用）
     */
    @PostMapping("/quickApprove/{auditId}")
    public AjaxResult quickApprove(@PathVariable Long auditId) {
        try {
            // 获取审核记录
            BusCarPackageAudit audit = auditService.selectBusCarPackageAuditById(auditId);
            if (audit == null) {
                return AjaxResult.error("审核记录不存在");
            }

            // 获取该流程实例的所有待办任务
            List<Task> tasks = taskService.createTaskQuery()
                    .processInstanceId(audit.getInstanceId())
                    .list();

            // 完成所有待办任务
            for (Task task : tasks) {
                Map<String, Object> variables = new HashMap<>();
                variables.put("approved", true);
                variables.put("comment", "系统快速审批通过");
                taskService.complete(task.getId(), variables);
            }

            // 更新业务数据为审核通过
            updateBusinessData(audit.getInstanceId(), true);

            return AjaxResult.success("快速审核通过成功");
        } catch (Exception e) {
            return AjaxResult.error("快速审核失败：" + e.getMessage());
        }
    }

    /**
     * 更新业务数据
     */
    private void updateBusinessData(String processInstanceId, Boolean approved) {
        try {
            // 查找对应的审核记录
            List<BusCarPackageAudit> auditList = auditService.selectBusCarPackageAuditList(new BusCarPackageAudit());
            for (BusCarPackageAudit audit : auditList) {
                if (processInstanceId.equals(audit.getInstanceId())) {
                    // 更新审核记录状态
                    if (approved) {
                        audit.setStatus(BusCarPackageAudit.STATUS_PASS);
                        auditService.updateBusCarPackageAudit(audit);
                        
                        // 更新服务项状态为审核通过
                        serviceItemService.changeAuditStatus(audit.getServiceItemId(), BusServiceItem.AUDITSTATUS_APPROVED);
                    } else {
                        audit.setStatus(BusCarPackageAudit.STATUS_REJECT);
                        auditService.updateBusCarPackageAudit(audit);
                        
                        // 更新服务项状态为审核拒绝
                        serviceItemService.changeAuditStatus(audit.getServiceItemId(), BusServiceItem.AUDITSTATUS_REPLY);
                    }
                    break;
                }
            }
        } catch (Exception e) {
            logger.error("更新业务数据失败", e);
        }
    }
}